package com.naizhuai.ui.components;

import android.app.Activity;
import com.naizhuai.R;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;

/**
 * @author：lichenxi
 * @date 2018/1/16 10
 * email：525603977@qq.com
 * Fighting
 */
public class SwipeRefreshDelegate {
    SwipeRefreshLayout swipeRefreshLayout;

    private OnSwipeRefreshListener providedListener;


    public interface OnSwipeRefreshListener {

        void onSwipeRefresh();
    }
    public SwipeRefreshDelegate(OnSwipeRefreshListener listener) {
        this.providedListener = listener;
    }

    public void attach(Activity activity) {
//        swipeRefreshLayout = activity.findViewById(R.id.swipe_refresh_layout);
        Init();
        trySetupSwipeRefresh();
    }

    private void Init() {
        swipeRefreshLayout.setProgressBackgroundColorSchemeResource(android.R.color.white);
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_light,
                android.R.color.holo_red_light, android.R.color.holo_orange_light,
                android.R.color.holo_green_light);
    }


    public void attach(View fragment) {
//        swipeRefreshLayout=fragment.findViewById(R.id.swipe_refresh_layout);
        Init();
        trySetupSwipeRefresh();
    }

    public void setRefresh(boolean requestDataRefresh) {
        if (swipeRefreshLayout == null) {
            return;
        }
        if (!requestDataRefresh) {
            swipeRefreshLayout.postDelayed(new Runnable() {
                @Override public void run() {
                    if (swipeRefreshLayout != null) {
                        swipeRefreshLayout.setRefreshing(false);
                    }
                }
            }, 1000);
        } else {
            swipeRefreshLayout.setRefreshing(true);
        }
    }

    public boolean isShowingRefresh() {
        return swipeRefreshLayout.isRefreshing();
    }

    public void setEnabled(boolean enable) {
        if (swipeRefreshLayout == null) {
            throw new IllegalAccessError("The SwipeRefreshLayout has not been initialized.");
        }
        swipeRefreshLayout.setEnabled(enable);
    }
    private void trySetupSwipeRefresh() {
        if (swipeRefreshLayout != null) {
            swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                @Override public void onRefresh() {
                    providedListener.onSwipeRefresh();
                }
            });
        }
    }
}
